package syncmaster;

import java.util.*;

public class RadarModel implements RadarModelInterface, Runnable {
	
	static ArrayList beatObservers = new ArrayList();
	ArrayList bpmObservers = new ArrayList();
    int bpm = 60;
	Thread thread;
	
	public RadarModel() {
		thread = new Thread(this);
		thread.start();
	}
	
	public void setBPM(int bpm) {
		this.bpm = bpm;
		notifyBPMObservers();
    }
 
	public int getBPM() {
		return bpm;
	}

	public int getRadarRate() {
		return bpm;
	}
	public void registerObserver(BeatObserver o) {
		beatObservers.add(o);
	}
	
	public void removeObserver(BeatObserver o) {
		int i = beatObservers.indexOf(o);
		if (i >= 0) {
			beatObservers.remove(i);
		}
	}

	public void notifyBeatObservers() {
		for(int i = 0; i < beatObservers.size(); i++) {
			BeatObserver observer = (BeatObserver)beatObservers.get(i);
			observer.updateBeat();
		}
	}

	public void registerObserver(BPMObserver o) {
		bpmObservers.add(o);
	}
	

	public void removeObserver(BPMObserver o) {
		int i = bpmObservers.indexOf(o);
		if (i >= 0) {
			bpmObservers.remove(i);
		}
	}

	public void notifyBPMObservers() {
		for(int i = 0; i < bpmObservers.size(); i++) {
			BPMObserver observer = (BPMObserver)bpmObservers.get(i);
			observer.updateBPM();
		}
	}
	
	//Devuelve un hash del tipo de modelo (usaod en DJVIew para cambiar etiquetas de botones)
	public int getHash() {
		return 102;
	}

	public void run() {
		for(;;)
			try {
				Thread.sleep(1000*60/bpm);
				notifyBeatObservers();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
	}
}
